import { _decorator, Component, Node } from 'cc';
import { DataManager } from 'db://assets/scripts/DataManager';
import { CardController } from 'db://assets/scripts/card/CardController';
import { DanmuChoicesController } from 'db://assets/scripts/ui/DanmuChoicesController';
import { SettlementResultController } from 'db://assets/scripts/ui/SettlementResultController';
import { ChooseRoleController } from 'db://assets/scripts/ui/ChooseRoleController';
import { RoundInfoController } from 'db://assets/scripts/ui/RoundInfoController';

const { ccclass, property } = _decorator;

export type CardItemInfo = {
  cardId: number;
  title: string;
  content: string;
  img?: string;
};
// 一个客户端游戏数据
export type RpsClientData = {
  role: string; // 游戏角色
  score: number; // 分数
  cards: ({
    // 手牌列表
    cardId: number;
    cardIndex: number;
    used: boolean;
    danmuCount: number; // 数量
    dark: boolean; // 是否暗牌
  } & CardItemInfo)[];
  selectedCard: number; // 选择的手牌
};
// 游戏数据
export type RpsServiceData = {
  roleList: string[];
  gameStatus: 'init' | 'playing' | '' | 'end'; // 初始化（等待） 进行中 游戏结束
  level: string; // 游戏关卡
  round: number; // 当前的回合
  totalRound: number; // 总回合数
  settlement: boolean; // 是否在结算中
  roundStartTime: number; // 回合开始时间
  roundEndTime: number; // 回合结束时间
  roundTime: number; // 回合时长
  settlementTime: number; // 结算时长
  winner: 'none' | string;
  clients: RpsClientData[];
};

@ccclass('GameManager')
export class GameManager extends Component {
  // 我方手牌列表
  @property(CardController)
  myCardsCl: CardController | null = null;
  // 对方手牌列表
  @property(CardController)
  enemyCardsCl: CardController | null = null;
  // 弹幕统计信息
  @property(DanmuChoicesController)
  danmuChoicesCl: DanmuChoicesController | null = null;
  // 敌方弹幕统计信息
  @property(DanmuChoicesController)
  enemyDanmuChoicesCl: DanmuChoicesController | null = null;
  // 回合结算
  @property(SettlementResultController)
  settlementResultCl: SettlementResultController | null = null;
  // 选择角色
  @property(ChooseRoleController)
  chooseRoleCl: ChooseRoleController | null = null;
  // 回合信息
  @property(RoundInfoController)
  roundInfoCl: RoundInfoController | null = null;

  private websocket: WebSocket | null = null;
  private gameData: RpsServiceData | null = null;

  start() {
    DataManager.instance.GameManager = this;
    this.closeCards();
    this.settlementResultCl.close();
    this.roundInfoCl.close();
    this.chooseRoleCl.open();
    // 建立链接
    this.connectToServer();
    // 测试数据
    // DataManager.instance.mock();
  }

  update(deltaTime: number) {
    // 游戏逻辑更新
  }

  // 连接到游戏服务器
  connectToServer() {
    this.websocket = new WebSocket('ws://localhost:8080/');

    this.websocket.onopen = () => {
      console.log('Connected to game server');
    };

    this.websocket.onmessage = (event) => {
      const message = JSON.parse(event.data);
      this.handleServerMessage(message);
    };

    this.websocket.onclose = () => {
      console.log('Disconnected from game server');
    };
  }

  // 处理服务器信息
  handleServerMessage(message: any) {
    const newData = message.data as RpsServiceData;
    switch (message.event) {
      case 'gameData':
        this.handleGameData(newData);
        break;
      case 'GmMessage':
        // 通知信息
        break;
      default:
        console.log('Unknown event:', message.event, message.data);
    }
  }

  // 选择角色加入游戏
  selectRole(role: string) {
    DataManager.instance.role = role;
    // 发送选择角色请求
    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
      this.websocket.send(
        JSON.stringify({
          event: 'joinGame',
          data: { role },
        })
      );
    }
  }

  // 处理服务端获取的游戏数据
  handleGameData(newData: RpsServiceData) {
    console.log('New game data:', newData);
    const { gameData, role } = DataManager.instance;
    DataManager.instance.updateGameData(newData);
    const myClient = newData.clients.find((c) => c.role === role);
    const enemyClient = newData.clients.find((c) => c.role !== role);
    const myCardList = myClient!.cards;
    const enemyCardList = enemyClient!.cards;
    // 开始游戏
    if (
      (gameData?.gameStatus === 'init' || !gameData) &&
      newData.gameStatus === 'playing'
    ) {
      // 关掉等待界面
      this.chooseRoleCl.closeWaiting();
      // 关掉结算界面
      this.settlementResultCl.close();
      // 初始化卡牌
      this.openCards();
      this.myCardsCl.init({ cardList: myCardList, position: 1 });
      this.enemyCardsCl.init({ cardList: enemyCardList, position: -1 });
      // 初始化弹幕统计信息
      this.danmuChoicesCl.init();
      this.enemyDanmuChoicesCl.init();
      this.danmuChoicesCl.render(false);
      this.enemyDanmuChoicesCl.render(true);
      // 回合信息
      this.roundInfoCl.open();
      console.log('Starting game');
    }
    // 回合结算
    else if (!gameData.settlement && newData.settlement) {
      this.settlementResultCl.render();
      console.log('Settlement');
    }
    // 新的回合
    else if (
      gameData.round !== newData.round &&
      newData.gameStatus === 'playing'
    ) {
      this.settlementResultCl.close();
      // 初始化卡牌
      this.myCardsCl.init({ cardList: myCardList, position: 1 });
      this.enemyCardsCl.init({ cardList: enemyCardList, position: -1 });
      // 初始化弹幕统计信息
      this.danmuChoicesCl.render(false);
      this.enemyDanmuChoicesCl.render(true);
      console.log(`New round: ${newData.round}`);
    }
    // 游戏结束
    else if (
      gameData.gameStatus === 'playing' &&
      newData.gameStatus === 'end'
    ) {
      this.settlementResultCl.render();
      console.log('Game ended');
    }
    // 游戏重回等待界面
    else if (newData.gameStatus === 'init') {
      this.closeCards();
      this.settlementResultCl.close();
      this.chooseRoleCl.openWaiting();
      this.roundInfoCl.close();
      console.log('Resetting game');
    }

    // 更新弹幕统计信息
    if (newData.gameStatus === 'playing') {
      this.danmuChoicesCl.render(false);
      this.enemyDanmuChoicesCl.render(true);
    }
  }

  // 隐藏手牌
  closeCards() {
    this.myCardsCl.node.active = false;
    this.enemyCardsCl.node.active = false;
    this.danmuChoicesCl.node.active = false;
    this.enemyDanmuChoicesCl.node.active = false;
  }
  // 显示手牌
  openCards() {
    this.myCardsCl.node.active = true;
    this.enemyCardsCl.node.active = true;
    this.danmuChoicesCl.node.active = true;
    this.enemyDanmuChoicesCl.node.active = true;
  }
  updateGameUI() {
    if (!this.gameData) return;

    // 根据游戏状态更新UI
    switch (this.gameData.gameStatus) {
      case 'init':
        this.showWaitingScreen();
        break;
      case 'playing':
        this.showGameScreen();
        break;
      case 'end':
        this.showResultScreen();
        break;
    }

    // 更新回合信息
    this.updateRoundInfo();

    // 更新玩家手牌信息
    this.updatePlayerHands();
  }

  showWaitingScreen() {
    // 显示等待界面
    console.log('Showing waiting screen');
  }

  showGameScreen() {
    // 显示游戏界面
    console.log('Showing game screen');
  }

  showResultScreen() {
    // 显示结果界面
    console.log('Showing result screen');
  }

  updateRoundInfo() {
    // 更新回合信息显示
    console.log(`Round: ${this.gameData?.round}/${this.gameData?.totalRound}`);
  }

  updatePlayerHands() {
    // 更新玩家手牌显示
    if (this.gameData?.clients) {
      this.gameData.clients.forEach((client) => {
        console.log(`Player ${client.role} cards:`, client.cards);
      });
    }
  }

  selectCard(cardIndex: number) {
    // 选择卡牌并发送到服务器
    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
      this.websocket.send(
        JSON.stringify({
          event: 'selectCard',
          data: { cardIndex },
        })
      );
    }
  }

  startGame() {
    // 发送开始游戏请求
    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
      this.websocket.send(
        JSON.stringify({
          event: 'startGame',
        })
      );
    }
  }
}
